package com.pin.zheng.xingmulibrary.util;


import android.content.Context;
import android.content.Intent;

import com.pin.zheng.xingmulibrary.app.AddresssKey;
import com.pin.zheng.xingmulibrary.app.xmConstant;
import com.pin.zheng.xingmulibrary.item.FileStruct;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
    //file文件读取成byte[]
    public static byte[] readFile(File file) {
        RandomAccessFile rf = null;
        byte[] data = null;
        try {
            rf = new RandomAccessFile(file, "r");
            data = new byte[(int) rf.length()];
            rf.readFully(data);
        } catch (Exception exception) {
            LogUtils.e(exception.getMessage());
            exception.printStackTrace();
        } finally {
            LogUtils.e("关闭File");
            closeQuietly(rf);
        }
        return data;
    }

    //关闭读取file
    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }


    /**
     * 解析HEX文件，读取每行并拆解成数据对象（包括第一行段地址）
     * @param filePath      String
     * @return              List<FileStruct>
     */
    public static List<FileStruct> analysisFile(Context context,String filePath) {
        File tempFile = new File(filePath);
        List<FileStruct> fileStructList = new ArrayList<>();
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = new FileInputStream(tempFile);
            //转成 reader 以 行 为单位读取文件
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            //当前行字符串
            String hexLineStr;
            while ((hexLineStr = bufferedReader.readLine()) != null) {
                if (!hexLineStr.startsWith(":", 0)) {
                    return null;
                }
                FileStruct hex = new FileStruct();
                if (hexLineStr.length() >= 11) {
                    hex.setStart(":");
                    byte[] data = HexUtil.hexString2ByteArray(hexLineStr.substring(1));//判断数据的正确是是不是0—F
                    if (data == null) return null;
                    //解析数据
                    hex.setLength(Integer.parseInt(hexLineStr.substring(1, 3), 16));
                    hex.setOffset(Integer.parseInt(hexLineStr.substring(3, 7), 16));
                    hex.setType(Integer.parseInt(hexLineStr.substring(7, 9), 16));

                    if (0x05 == hex.getType()|| 0x01 == hex.getType()) {//不处理05类型的数据,和01的结尾数据
                        continue;
                    }
                    if (hex.getLength() > 0) {
                        hex.setData(hexLineStr.substring(9, 9 + hex.getLength() * 2));
//                        LogUtils.e(hex.getData());
                    }
                }
                if (!HexUtil.checkValue(hexLineStr)) return null;
                //判断数据类型是否合法,只处理00有效数据
                fileStructList.add(hex);
            }
        } catch (Exception e) {
            context.sendBroadcast(new Intent(xmConstant.ACTION_UPDATE_HEX_VALUE_NO));
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileStructList;
    }


    /**
     * 解析HEX文件，读取每行并拆解成数据对象（包括第一行段地址）
     * @param filePath      String
     * @return              List<FileStruct>
     */
    public static List<String> analysisStringFile(Context context,String filePath) {
        File tempFile = new File(filePath);
        List<FileStruct> fileStructList = new ArrayList<>();
        List<String> strings=new ArrayList<>();
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = new FileInputStream(tempFile);
            //转成 reader 以 行 为单位读取文件
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            //当前行字符串
            String hexLineStr;
            while ((hexLineStr = bufferedReader.readLine()) != null) {
                if (!hexLineStr.startsWith(":", 0)) {
                    return null;
                }
                FileStruct hex = new FileStruct();
                if (hexLineStr.length() >= 11) {
                    hex.setStart(":");
                    byte[] data = HexUtil.hexString2ByteArray(hexLineStr.substring(1));//判断数据的正确是是不是0—F
                    if (data == null) return null;
                    //解析数据
                    hex.setLength(Integer.parseInt(hexLineStr.substring(1, 3), 16));
                    hex.setOffset(Integer.parseInt(hexLineStr.substring(3, 7), 16));
                    hex.setType(Integer.parseInt(hexLineStr.substring(7, 9), 16));

                    if (0x05 == hex.getType()|| 0x01 == hex.getType()) {//不处理05类型的数据,和01的结尾数据
                        continue;
                    }
                    if (hex.getLength() > 0) {
                        hex.setData(hexLineStr.substring(9, 9 + hex.getLength() * 2));
//                        LogUtils.e(hex.getData());
                    }
                }

                if (!HexUtil.checkValue(hexLineStr)) return null;
                //判断数据类型是否合法,只处理00有效数据
                fileStructList.add(hex);
//                LogUtils.e(hexLineStr.substring(1,hexLineStr.length()));
                strings.add(hexLineStr.substring(1,hexLineStr.length()));
            }
        } catch (Exception e) {
            context.sendBroadcast(new Intent(xmConstant.ACTION_UPDATE_HEX_VALUE_NO));
            e.printStackTrace();
            LogUtils.e(e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                LogUtils.e(e.getMessage());
                e.printStackTrace();
            }
        }
//        return fileStructList;
        return strings;
    }


    /**
     * 读bin文件
     *
     * @param filePath
     * @param len
     * @return
     */
    public static List<String> readBinFileList(String filePath, int len) {
        List<String> list = new ArrayList<>();
        File f = new File(filePath);
        byte[] b = new byte[len];
        int rl;
        String[] t = new String[len];
        try {
            FileInputStream fs = new FileInputStream(f);
            while ((rl = fs.read(b)) != -1) {
                list.add(byteToString(b));
//                LogUtils.e(byteToString(b));
            }
            byte[] bytes = new byte[(int) (f.length() % len)];
            rl = fs.read(bytes);
            LogUtils.e(byteToString(bytes));
//            if (rl != len) {
//                LogUtils.e("read len:" + rl);
//            }
            fs.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        byteToString(b, t);
        return list;
    }

    private static String byteToString(byte[] b) {
        StringBuffer string = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            string.append(String.format("%02X", (int) (b[i] & 0xFF)));
        }
        return string.toString();
    }

    public static String getAllDataFileNameStr(String folderPath){
        StringBuffer stringBuffer=new StringBuffer();
        File file = new File(folderPath);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                LogUtils.e("文     件：" + tempList[i].getName());
//                String fileName = tempList[i].getName();
//                if (fileName.endsWith(".png")){    //  根据自己的需要进行类型筛选
//                fileList.add(fileName);
//                }
                stringBuffer.append(tempList[i].getName()+",");
            }
        }
        return stringBuffer.toString();
    }

}
